import UIKit
import Flutter

@main
@objc class AppDelegate: FlutterAppDelegate {
    let share = Share()
    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        GeneratedPluginRegistrant.register(with: self)
        
        let vc = window.rootViewController as? FlutterViewController, engine = vc?.engine
        if let engine = engine {
            engine.navigationChannel.setMethodCallHandler { call, result in
                let method = call.method
                switch method {
                case "share":
                    self.share.share(call.arguments as! String, from: vc!)
                    self.share.onDone = {
                        result(nil)
                    }
                    break
                default: break
                    
                }
            }
        }
        
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }
    
    override func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        let vc = window.rootViewController as? FlutterViewController, engine = vc?.engine
        if let engine = engine {
            let data = try? Data(contentsOf: url)
            guard data != nil else {
                return true
            }
            var path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last
            path?.append("/get.dsp")
            
            guard path != nil else {
                return true
            }
            
            if FileManager.default.fileExists(atPath: path!) {
                try? FileManager.default.removeItem(atPath: path!)
            }
            
            try? data?.write(to: URL(fileURLWithPath: path!))
            
            let str = try? String(contentsOf: URL(fileURLWithPath: path!))
            guard str != nil else {
                return true
            }
            
            engine.navigationChannel.invokeMethod("parseFile", arguments: ["content": str])
        }
        return true
    }
}

//extension FlutterViewController {
//    open override var preferredScreenEdgesDeferringSystemGestures: UIRectEdge {
//        return UIRectEdge.bottom
//    }
//    
//    open override var prefersHomeIndicatorAutoHidden: Bool {
//        return true
//    }
//    
//    open override func viewDidAppear(_ animated: Bool) {
//        super.viewDidAppear(true)
//        view.backgroundColor = .red
//        if #available(iOS 11.0, *) {
//            //Notifies UIKit that your view controller updated its preference regarding the visual indicator
//            setNeedsUpdateOfHomeIndicatorAutoHidden()
//        }
//    }
//}
